import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/*
该案刘是用来检验用户名是否存在
   1: 服务器响应的数据,在客户端使用时,要想当做json数据格式使用
      * $.get(type): 将get方法的最后一个参数指定为"json"
      * 或者在服务器端设置MIME类型
         response.setContenType("application/json;charset=utf-8");

*/

@WebServlet("/findUserServlet")
public class FindUserServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     //1.获取用户名
        String cc = request.getParameter("username");
        //2.调用service层判断用户是否存在
        //期望服务器响应回的数据格式: {"userExist":"true","msg":"此用户名太受欢迎,请更换一个"}
        //                  {"userExist":"false","mag":"此用户名可用"}
        response.setContentType("text/html;charset=utf-8");
        Map<String,Object> map=new HashMap<String,Object>();
        if ("tony".equals(cc)){
            //存在
            map.put("userExist",true);
            map.put("msg","此用户名太受欢迎,请更换一个");
        }else{
            //不存在
            map.put("userExist","false");
            map.put("msg","此用户名可用");
        }

        //将map转为json,并且传给客户端(就是写到页面上)
        ObjectMapper dd=new ObjectMapper();
        dd.writeValue(response.getWriter(),map);

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       this.doPost(request,response);
    }
}
